from typing import Optional, Dict

from datetime import datetime, timedelta

import jwt
from jwt import PyJWTError

from config import settings


def create_access_token(data: dict):

    """创建访问令牌"""

    to_encode = data.copy()

    expire = datetime.now() + timedelta(days=7)

    to_encode.update({"exp": expire})

    encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm="HS256")

    return encoded_jwt

def verify_access_token(token: str) :
    try:
        # 解码令牌，使用HS256算法，同时会验证签名以及检查令牌是否过期等
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
        exp = payload.get("exp")
        if exp:
            # 将过期时间戳（通常是Unix时间戳形式，这里按这种情况处理，如果不是需要适当调整）转换为datetime对象
            expiration_time = datetime.fromtimestamp(exp)
            if expiration_time > datetime.now():
                return payload
            else:
                return None
        return payload
    except PyJWTError:
        return None

# result = verify_access_token(
#     'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJvSjFkZTVFd2tZbTRKQXZqS3VKdEYybWlidk9VIiwiZXhwIjoxNzM2MTIwODEzfQ.6JGzGZ0_6tGcDA0a-IK906GHNRGkrJgnlex5e4BCksE'
# )
#
# print(result)